//
//  FDNewCalendarView.m
//  MobileOffice
//
//  Created by jjkj on 16/11/17.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "FDNewCalendarView.h"
#import "FDCalendarItem.h"

#define Weekdays @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"]

static NSDateFormatter *dateFormattor;

@interface FDNewCalendarView () <UIScrollViewDelegate, FDCalendarItemDelegate>

@property (strong, nonatomic) NSDate *date;

@property (strong, nonatomic) UIButton *titleButton;
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) FDCalendarItem *leftCalendarItem;
@property (strong, nonatomic) FDCalendarItem *centerCalendarItem;
@property (strong, nonatomic) FDCalendarItem *rightCalendarItem;
@property (strong, nonatomic) UIView *backgroundView;
@property (strong, nonatomic) UIView *datePickerView;
@property (strong, nonatomic) UIDatePicker *datePicker;
@property (strong, nonatomic) NSDate *timeDate;

@end

@implementation FDNewCalendarView

- (instancetype)initWithCurrentDate:(NSDate *)date {
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        self.date = date;
        self.timeDate=date;
        [self setupTitleBar];
        [self setupWeekHeader];
        [self setupCalendarItems];
        [self setupScrollView];
        [self creatDatePickerView];
        [self setFrame:CGRectMake(0, 0, DeviceWidth,_datePickerView.y+_datePickerView.height)];
        
        [self setCurrentDate:self.date];
    }
    return self;
}

#pragma mark - Custom Accessors

- (UIView *)backgroundView {
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame: self.bounds];
        _backgroundView.backgroundColor = [UIColor clearColor];
        _backgroundView.alpha = 0;
        
        //        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideDatePickerView)];
        //        [_backgroundView addGestureRecognizer:tapGesture];
    }
    
    [self addSubview:_backgroundView];
    
    return _backgroundView;
}

//dateViewPicker
- (void)creatDatePickerView {
    _datePickerView = [[UIView alloc] initWithFrame:CGRectMake(10, _scrollView.y+_scrollView.height, IPHONE_WIDTH-20, 70)];
    _datePickerView.backgroundColor = [UIColor whiteColor];
    _datePickerView.clipsToBounds = YES;
    [self addSubview:_datePickerView];
    
    UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, _datePickerView.height-60, _datePickerView.width/2, 50)];
    cancelButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelSelectCurrentDate) forControlEvents:UIControlEventTouchUpInside];
    [_datePickerView addSubview:cancelButton];
    
    UIButton *okButton = [[UIButton alloc] initWithFrame:CGRectMake(_datePickerView.width/2, cancelButton.y, cancelButton.width, cancelButton.height)];
    okButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [okButton setTitle:@"确定" forState:UIControlStateNormal];
    [okButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [okButton addTarget:self action:@selector(sureButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_datePickerView addSubview:okButton];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, okButton.y, _datePickerView.width, 1)];
    lineView.backgroundColor = BACKCOLOR_GRAY;
    [_datePickerView addSubview:lineView];
    
    UIView *line2View = [[UIView alloc] initWithFrame:CGRectMake(cancelButton.x+cancelButton.width, okButton.y, 1, 60)];
    line2View.backgroundColor = BACKCOLOR_GRAY;
    [_datePickerView addSubview:line2View];
    //
    //    return _datePickerView;
}


- (UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.datePickerMode = UIDatePickerModeTime;
        _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"en_GB"];
        [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged ];
        
        _datePicker.frame = CGRectMake(0, 10, _datePickerView.width, 150);
    }
    
    return _datePicker;
}

#pragma mark - Private

- (NSString *)stringFromDate:(NSDate *)date formatStr:(NSString *)formatStr{
    if (!dateFormattor) {
        dateFormattor = [[NSDateFormatter alloc] init];
    }
    [dateFormattor setDateFormat:formatStr];
    return [dateFormattor stringFromDate:date];
}

// 设置上层的titleBar
- (void)setupTitleBar {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, IPHONE_WIDTH-20, 44)];
    titleView.backgroundColor = COLOR_MIDBLUE;
    [self addSubview:titleView];
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 32, 24)];
    [leftButton setImage:[UIImage imageNamed:@"k_ic_jt_left"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(setPreviousMonthDate) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:leftButton];
    
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(titleView.frame.size.width - 37, 10, 32, 24)];
    [rightButton setImage:[UIImage imageNamed:@"k_ic_jt_right"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(setNextMonthDate) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:rightButton];
    
    _titleButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
    _titleButton.titleLabel.textColor = [UIColor whiteColor];
    //_titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _titleButton.center = titleView.center;
    _titleButton.titleLabel.font=FONT_15;
    //[_titleButton addTarget:self action:@selector(showDatePicker) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:_titleButton];
    
}

// 设置星期文字的显示
- (void)setupWeekHeader {
    NSInteger count = [Weekdays count];
    CGFloat offsetX = 10;
    UIView *weekView=[[UIView alloc]initWithFrame:CGRectMake(offsetX, 44, (DeviceWidth - 20), 51)];
    weekView.backgroundColor=[UIColor whiteColor];
    [self addSubview:weekView];
    for (int i = 0; i < count; i++) {
        UILabel *weekdayLabel = [[UILabel alloc] initWithFrame:CGRectMake((DeviceWidth - 20) / count*i, 10, (DeviceWidth - 20) / count, 20)];
        weekdayLabel.textAlignment = NSTextAlignmentCenter;
        weekdayLabel.text = Weekdays[i];
        weekdayLabel.backgroundColor=[UIColor whiteColor];
        if (i == 0 || i == count - 1) {
            weekdayLabel.textColor = COLOR_MIDBLUE;
        } else {
            weekdayLabel.textColor = [UIColor blackColor];
        }
        
        [weekView addSubview:weekdayLabel];
    }
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, weekView.width, 1)];
    lineView.backgroundColor = BACKCOLOR_GRAY;
    [weekView addSubview:lineView];
}

// 设置包含日历的item的scrollView
- (void)setupScrollView {
    self.scrollView.backgroundColor=[UIColor clearColor];
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.scrollEnabled=NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.scrollView setFrame:CGRectMake(0, 95, DeviceWidth, self.centerCalendarItem.frame.size.height)];
    self.scrollView.contentSize = CGSizeMake(3 * self.scrollView.frame.size.width, self.scrollView.frame.size.height);
    self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width, 0);
    [self addSubview:self.scrollView];
}

// 设置3个日历的item
- (void)setupCalendarItems {
    self.scrollView = [[UIScrollView alloc] init];
    
    self.leftCalendarItem = [[FDCalendarItem alloc] init];
    [self.scrollView addSubview:self.leftCalendarItem];
    
    CGRect itemFrame = self.leftCalendarItem.frame;
    itemFrame.origin.x = DeviceWidth;
    self.centerCalendarItem = [[FDCalendarItem alloc] init];
    self.centerCalendarItem.frame = itemFrame;
    self.centerCalendarItem.delegate = self;
    [self.scrollView addSubview:self.centerCalendarItem];
    
    itemFrame.origin.x = DeviceWidth * 2;
    self.rightCalendarItem = [[FDCalendarItem alloc] init];
    self.rightCalendarItem.frame = itemFrame;
    [self.scrollView addSubview:self.rightCalendarItem];
}

// 设置当前日期，初始化
- (void)setCurrentDate:(NSDate *)date {
    self.centerCalendarItem.date = date;
    self.leftCalendarItem.date = [self.centerCalendarItem previousMonthDate];
    self.rightCalendarItem.date = [self.centerCalendarItem nextMonthDate];
    
    [self.titleButton setTitle:[self stringFromDate:self.centerCalendarItem.date formatStr:@"yyyy年MM月"] forState:UIControlStateNormal];
}

// 重新加载日历items的数据
- (void)reloadCalendarItems {
    CGPoint offset = self.scrollView.contentOffset;
    
    if (offset.x == self.scrollView.frame.size.width) { //防止滑动一点点并不切换scrollview的视图
        return;
    }
    
    if (offset.x > self.scrollView.frame.size.width) {
        [self setNextMonthDate];
    } else {
        [self setPreviousMonthDate];
    }
    
    self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width, 0);
}

//- (void)showDatePickerView {
//    [UIView animateWithDuration:0.25 animations:^{
//        self.backgroundView.alpha = 0.4;
//        self.datePickerView.frame = CGRectMake(0, 44, self.frame.size.width, 250);
//    }];
//}
//
//- (void)hideDatePickerView {
//    [UIView animateWithDuration:0.25 animations:^{
//        self.backgroundView.alpha = 0;
//        self.datePickerView.frame = CGRectMake(0, 44, self.frame.size.width, 0);
//    } completion:^(BOOL finished) {
//        [self.backgroundView removeFromSuperview];
//        [self.datePickerView removeFromSuperview];
//    }];
//}

#pragma mark - SEL

// 跳到上一个月
- (void)setPreviousMonthDate {
    [self setCurrentDate:[self.centerCalendarItem previousMonthDate]];
}

// 跳到下一个月
- (void)setNextMonthDate {
    [self setCurrentDate:[self.centerCalendarItem nextMonthDate]];
}

//- (void)showDatePicker {
//
////    [self showDatePickerView];
//}

// 确定按钮
- (void)sureButtonClick{
    //NSLog(@"date------->%@",[self stringFromDate:self.timeDate formatStr:@"yyyy-MM-dd HH:mm:ss"]);
    NSString *dateStr=[NSString stringWithFormat:@"%@",[self stringFromDate:self.date formatStr:@"yyyy-MM-dd"]];
    if (_timeStrBlock) {
        _timeStrBlock(dateStr);
    }
    if (_cancleBlock) {
        _cancleBlock();
    }
    NSLog(@"dateStr---------->%@",dateStr);
    //[self setCurrentDate:self.datePicker.date];
    //[self hideDatePickerView];
}

- (void)cancelSelectCurrentDate {
    if (_cancleBlock) {
        _cancleBlock();
    }
    //[[NSNotificationCenter defaultCenter]postNotificationName:@"datePickViewCancel" object:nil];
}

-(void)dateChanged:(UIDatePicker *)datePicker{
    self.timeDate=datePicker.date;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self reloadCalendarItems];
}

#pragma mark - FDCalendarItemDelegate

- (void)calendarItem:(FDCalendarItem *)item didSelectedDate:(NSDate *)date {
    self.date = date;
    [self setCurrentDate:self.date];
}
- (void)dealloc{
    NSLog(@"FDcalendarDealloc");
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
